package com.zhixun.mobile.modules.member.web;

import java.io.File;


import java.io.UnsupportedEncodingException;
import java.net.URLEncoder;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import com.boxin.framework.base.dao.DaoHelper;
import com.boxin.ims.modules.momarketing.common.QRCodeUtils;
import com.boxin.ims.modules.sys.utils.ImageUtils;
import com.boxin.ims.modules.wechat.entity.Lottery;
import com.boxin.ims.modules.wechat.entity.MemberScore;
import com.boxin.ims.modules.wechat.entity.RecommendConfig;
import com.boxin.ims.modules.wechat.entity.WeChat;
import com.boxin.ims.modules.wechat.entity.WechatMember;
import com.boxin.ims.modules.wechat.score.entity.ExchangeRecord;
import com.boxin.ims.modules.wechat.score.entity.ScoreExchange;
import com.boxin.ims.modules.wechat.score.service.ExchangeRecordService;
import com.boxin.ims.modules.wechat.score.service.ScoreExchangeService;
import com.boxin.ims.modules.wechat.service.LotteryService;
import com.boxin.ims.modules.wechat.service.MemberScoreService;
import com.boxin.ims.modules.wechat.service.RecommendConfigService;
import com.boxin.ims.modules.wechat.service.WeChatService;
import com.boxin.ims.modules.wechat.service.WechatDaoHelper;
import com.boxin.ims.modules.wechat.service.WechatMemberService;
import com.boxin.ims.modules.wechat.utils.ScoreUtils;
import com.boxin.ims.modules.wechat.utils.WechatInterfaceUtils;
import com.boxin.ims.modules.wechat.utils.WechatUtils;
import com.thinkgem.jeesite.common.config.Global;
import com.thinkgem.jeesite.common.utils.CacheUtils;
import com.thinkgem.jeesite.common.utils.CookieUtils;
import com.thinkgem.jeesite.common.utils.DateUtils;
//import com.thinkgem.jeesite.common.utils.JedisUtils;
import com.thinkgem.jeesite.modules.sys.entity.User;
import com.zhixun.mobile.common.utils.RequestUtil;
import com.zhixun.mobile.common.utils.StringUtils;
import com.zhixun.mobile.modules.base.web.BaseController;
import com.zhixun.mobile.modules.member.service.MemberService;
import com.zhixun.mobile.sys.utils.AssertUtils;

@Controller
@RequestMapping(value = Global.FRONT_PATH+"/expand")
public class ExpandFrontController extends BaseController {
	@Autowired
	private MemberScoreService memberScoreService;
	
	@Autowired
	private WechatMemberService wechatMemberService;
	
	@Autowired
	private RecommendConfigService recommendConfigService;
	
	@Autowired
	private LotteryService lotteryService;
	
	@Autowired
	private WechatDaoHelper wechatDaoHelper;
	
	@Autowired
	private WeChatService weChatService;
	
	@Autowired
	private ScoreExchangeService scoreExchangeService;
	
	@Autowired
	private MemberService memberService;
	
	@Autowired
	private ExchangeRecordService exchangeRecordService;
	
	
	@Autowired
	private  DaoHelper daoHelper;

	public RecommendConfig getRecommendConfig(String uid){
		String key = "recommend_config_"+uid;
		Object object = CacheUtils.get(key);
		if(object!=null){
			return (RecommendConfig) object;
		}else{
//			object =	JedisUtils.getObject(key);
			object = CacheUtils.get(key);
			if(object!=null){
				return (RecommendConfig) object;
			}else{
				RecommendConfig config = recommendConfigService.getByUserId(Long.parseLong(uid));
//				JedisUtils.setObject(key, config, 0);
				CacheUtils.put(key, config);
				return config;
			}
		}
	}
	
	/**
	 * 获得oauth路径 url传入
	 * @param url
	 * @param uid
	 * @param request
	 * @return
	 */
	public String getOAuthUrl(String url, String uid, HttpServletRequest request, HttpServletResponse response) {

		String path = request.getContextPath();
		String basePath = request.getScheme() + "://" + request.getServerName() + path;

		WeChat weChat = weChatService.getWeChatByUserId(Long.parseLong(uid));
		String state = uid;
		url = url.replace("null", "");
		CookieUtils.setCookie(response, "redirectUrl",basePath + Global.getFrontPath() + url);

		System.out.println(basePath);

		String redirectUrl = URLEncoder.encode(basePath + "/f/oauth/redirectGainMember");
		
		String returnUrl = "https://open.weixin.qq.com/connect/oauth2/authorize?appid="	+ weChat.getAppId()	+ "&redirect_uri="	+ redirectUrl 
							+ "&response_type=code&scope=snsapi_userinfo&state=" + state + "&connect_redirect=1#wechat_redirect";
		
		return returnUrl;
	}
	
	
	/**
	 * 三级推广：首页
	 * @param request
	 * @param response
	 * @param model
	 * @return
	 */
	@RequestMapping(value = "index")
	public String index(HttpServletRequest request,HttpServletResponse response, Model model) {
		
		String uid = request.getParameter("uid");
		String wechatId = request.getParameter("wechatId");
		
		if (StringUtils.isEmpty(wechatId)) {
			String url = getOAuthUrl("/expand/index",uid, request, response);
			return "redirect:" + url;
		}
		
		WechatMember member = wechatMemberService.getByWechatMemberId(new User(Long.parseLong(uid)), wechatId);//核销人员
		
		RecommendConfig config = getRecommendConfig(uid);
		
		Map<String, Object> params = new HashMap<String, Object>();
		params.put("userId", uid);
		params.put("parentCode", member.getRecommendCode());
		params.put("startTime", config.getStartTime());
		params.put("endTime", config.getEndTime());
		List<Map<String, String>> list = wechatDaoHelper.findMemberByParentCode(params);
		
		model.addAttribute("renqi", list.size());
		model.addAttribute("member", member);
		model.addAttribute("uid", uid);
		model.addAttribute("wechatId", wechatId);
		
		model.addAttribute("recommendConfig", config);
		
		return "/modules/member/themes/expand/index";
	}
	
	/**
	 * 三级推广：排行榜
	 * @param request
	 * @param response
	 * @param model
	 * @return
	 */
	@RequestMapping(value = "rankList")
	public String rankList(HttpServletRequest request,HttpServletResponse response, Model model){

		String uid = request.getParameter("uid");
		String wechatId = request.getParameter("wechatId");
		
		if (StringUtils.isEmpty(wechatId)) {
			String url = getOAuthUrl("/expand/rankList",uid, request, response);
			return "redirect:" + url;
		}
		WechatMember member = wechatMemberService.getByWechatMemberId(new User(Long.parseLong(uid)), wechatId);//核销人员
		model.addAttribute("member", member);
		
		Map<String, Object> params = new HashMap<String, Object>();
		params.put("userId", uid);
		List<Map<String, String>> list = wechatDaoHelper.findMemberByRecommendScore(params);
		
		model.addAttribute("list", list);
		
		RecommendConfig config = getRecommendConfig(uid);
		model.addAttribute("recommendConfig", config);
		
		return "/modules/member/themes/expand/rankList";
	}
	
	/**
	 * 我的推荐
	 * @param request
	 * @param response
	 * @param model
	 * @return
	 */
	@RequestMapping(value = "myCommend")
	public String myCommend(HttpServletRequest request,HttpServletResponse response, Model model){

		String uid = request.getParameter("uid");
		String wechatId = request.getParameter("wechatId");
		
		if (StringUtils.isEmpty(wechatId)) {
			String url = getOAuthUrl("/expand/myCommend",uid, request, response);
			return "redirect:" + url;
		}
		WechatMember member = wechatMemberService.getByWechatMemberId(new User(Long.parseLong(uid)), wechatId);//核销人员
		
		RecommendConfig config = getRecommendConfig(uid);
		Map<String, Object> params = new HashMap<String, Object>();
		params.put("userId", uid);
		params.put("parentCode", member.getRecommendCode());
		params.put("startTime", config.getStartTime());
		params.put("endTime", config.getEndTime());
		List<Map<String, String>> list = wechatDaoHelper.findMemberByParentCode(params);
		
		model.addAttribute("wechatMemberList", list);
		model.addAttribute("membersCount", list.size());
		
		return "/modules/member/themes/expand/myCommend";
	}

	@RequestMapping(value = "jifen")
	public String jifen(HttpServletRequest request,HttpServletResponse response, Model model) {
		String uid =request.getParameter("uid");
		String wechatId = request.getParameter("wechatId");
		
		if (StringUtils.isEmpty(wechatId)) {
			String url = getOAuthUrl("/expand/jifen",uid, request, response);
			return "redirect:" + url;
		}
		WechatMember member = wechatMemberService.getByWechatMemberId(new User(Long.parseLong(uid)), wechatId);//核销人员
		
		
		model.addAttribute("uid", uid);
		model.addAttribute("wechatId", wechatId);
		model.addAttribute("memberId", member.getId());
		return "modules/member/themes/expand/jifen";
	}
	
	@ResponseBody
	@RequestMapping(value = "jifenajax")
	public String jifenajax(HttpServletRequest request,HttpServletResponse response, Model model) {
		String uid =request.getParameter("uid");
		String memberId = request.getParameter("memberId");
		String jifen = request.getParameter("jifen");		//1 ：积分获取		-1：积分使用
		
		Integer first = RequestUtil.getInteger(request, "first");
		if (first == null) {
			first = 1;
		}
		
		Map<String, Object> result = new  HashMap<String,Object>();
		
		RecommendConfig config = getRecommendConfig(uid);
		Map<String, Object> params = new HashMap<String, Object>();
		params.put("userId", uid);
		params.put("memberId", memberId);
		params.put("type", MemberScore.TYPE_RECOMMEND_TEMP);
		params.put("startTime", config.getStartTime());
		params.put("endTime", config.getEndTime());
		if(jifen == null || Integer.parseInt(jifen)>0){
			params.put("addScore", "1");
		}else{
			params.put("minusScore", "-1");
		}
		Integer count = wechatDaoHelper.selectMemberScoreCount(params);
		
		if((count-(first*20))>0){
			result.put("next", true);
		}else{
			result.put("next", false);
		}
		
		params.put("firstNum", (first-1)*20);
		
		List<Map<String, String>>   list =  wechatDaoHelper.selectMemberScore(params);
		result.put("result", list);
		
		writeJson(request, response, result);
		return null;
	}
	
	@RequestMapping(value = "newMemberHelp")
	public String newMemberHelp(HttpServletRequest request,HttpServletResponse response, Model model){
		String uid = request.getParameter("uid");
		RecommendConfig config = getRecommendConfig(uid);
		model.addAttribute("config", config);
		return "modules/member/themes/expand/newMemberHelp";
	}

	@RequestMapping(value = "test")
	public String test(HttpServletRequest request,HttpServletResponse response, Model model) throws Exception {
		
		String uid = request.getParameter("uid");
		String wechatId = request.getParameter("wechatId");
		
		WechatMember member = wechatMemberService.getByWechatMemberId(new User(Long.parseLong(uid)), wechatId);//核销人员
		
		RecommendConfig recommendConfig = getRecommendConfig(uid);
		
		String picFilePath = WechatUtils.getRecommendSavePath(request)+File.separator+"nadu_recommend_1465266463917.jpg";
		System.out.println("===="+picFilePath+"=="+File.separator);
		//生成推广图片
		String tuiGuang = ImageUtils.posterImage(picFilePath, member, "gQHY8DoAAAAAAAAAASxodHRwOi8vd2VpeGluLnFxLmNvbS9xL0IwT3Z6Wm5saE9UOTVQZTk3bTlnAAIE05plUwMEAAAAAA==", recommendConfig, request);
		System.out.println(tuiGuang);
		return null;
	}
	
	
	/**
	 * 三级推广：活动期间的积分排行榜
	 * @param request
	 * @param response
	 * @param model
	 * @return
	 */
	@RequestMapping(value = "scoreRankList")
	public String scoreRankList(HttpServletRequest request,HttpServletResponse response, Model model){

		String uid = request.getParameter("uid");
		String wechatId = request.getParameter("wechatId");
		
		if (StringUtils.isEmpty(wechatId)) {
			String url = getOAuthUrl("/expand/scoreRankList",uid, request, response);
			return "redirect:" + url;
		}
		WechatMember member = wechatMemberService.getByWechatMemberId(new User(Long.parseLong(uid)), wechatId);
		
		RecommendConfig recommendConfig = getRecommendConfig(uid);
		
		Map<String, Object> params = new HashMap<String, Object>();
		params.put("userId", uid);
		params.put("startTime", recommendConfig.getStartTime());
		params.put("endTime", recommendConfig.getEndTime());
		params.put("type", MemberScore.TYPE_RECOMMEND_TEMP);
		List<Map<String, Object>> scoreRankList = wechatDaoHelper.findScoreRankList(params);
		
		model.addAttribute("member", member);
		model.addAttribute("scoreRankList", scoreRankList);
		model.addAttribute("recommendConfig", recommendConfig);
		
		if(recommendConfig.getRankNum() != null && recommendConfig.getRankNum()>0){
			model.addAttribute("rankNum", recommendConfig.getRankNum());
		}else{
			model.addAttribute("rankNum", scoreRankList.size());
		}
		
		
		User user = new User(recommendConfig.getUserId());
		Lottery lottery = new Lottery();
		lottery.setUser(user);
		lottery.setType("7");
		lottery.setSourceId(recommendConfig.getId());
		lottery.setSourceType("3");
		List<Lottery> lotteryList = lotteryService.expandFindList(lottery);
		
		//便利会员
		out:for (int j = 0; j < scoreRankList.size(); j++) {
			Object o = scoreRankList.get(j).get("wechat_id");
			if(o == null){
				 continue;
			}
			String mWechatId = o.toString();
			if(StringUtils.isBlank(mWechatId) || !wechatId.equals(mWechatId)){
				 continue;
			}else{
				//便利奖品
				for(int n = 0; n < lotteryList.size(); n++){
					//判断用户得奖等级
					if(j+1>=lotteryList.get(n).getUpper() && j+1<=lotteryList.get(n).getLower()){
						model.addAttribute("content", "你得到了第"+(j+1)+"名哟，你的奖品是"+lotteryList.get(n).getName());
						model.addAttribute("isPrize","YES");
						break out;
					}
				}
			}
			
		}
		
		Date date = new Date();
		
		String yers = DateUtils.formatDate(recommendConfig.getEndTime(), "yyyy");
		String month = DateUtils.formatDate(recommendConfig.getEndTime(), "MM");
		String day = DateUtils.formatDate(recommendConfig.getEndTime(), "dd");
		String hours = DateUtils.formatDate(recommendConfig.getEndTime(), "HH");
		
		model.addAttribute("yers", yers);
		model.addAttribute("month", month);
		model.addAttribute("day", day);
		model.addAttribute("hours", hours);
		
		//判断活动是否结束
		if(recommendConfig.getEndTime().getTime()<date.getTime()){
			model.addAttribute("isEnd", "YES");
		}
		model.addAttribute("uid", uid);
		model.addAttribute("wechatId", wechatId);
		
		return "/modules/member/themes/expand/scoreRankList";
	}
	
	/**
	 * 积分兑换奖品列表
	 * @param model
	 * @param request
	 * @param response
	 * @return
	 */
	@RequestMapping(value = "toExchangeList")
	public String toExchangeList(Model model, HttpServletRequest request,HttpServletResponse response) {
		String wechatId = request.getParameter("wechatId"); // OpenId
		String uid = request.getParameter("uid");
		if (StringUtils.isBlank(wechatId)) { // 没有登录先进入登录页面
			String url = getOAuthUrl("/expand/toExchangeList", uid, request, response);
			return "redirect:" + url;
		}
		RecommendConfig config = getRecommendConfig(uid);
		WechatMember wechatMember = wechatMemberService.getByWechatMemberId(new User(Long.parseLong(uid)), wechatId);
		// 兑换的列表
		ScoreExchange scoreExchange = new ScoreExchange();
		scoreExchange.setUser(wechatMember.getUser());
		scoreExchange.setPayType("2");
		List<ScoreExchange> scoreExchangeList = scoreExchangeService.find(scoreExchange);
		
		model.addAttribute("scoreExchangeList", scoreExchangeList);
		model.addAttribute("wechatMember", wechatMember);
		model.addAttribute("wechatId", wechatId);
		model.addAttribute("uid", uid);
		model.addAttribute("config", config);
		return "/modules/member/themes/expand/exchangeScore";
	}
	
	/**
	 * 积分奖品详情
	 * @param model
	 * @param request
	 * @param response
	 * @return
	 */
	@RequestMapping(value = "toScoreExchange")
	public String toExchangepro(Model model, HttpServletRequest request,HttpServletResponse response) {
		String uid = request.getParameter("uid");
		String wechatId = request.getParameter("wechatId"); // OpenId
		String scoreExchangeId = request.getParameter("scoreExchangeId"); // OpenId
		
		if (StringUtils.isBlank(wechatId)) { // 没有登录先进入登录页面
			String url = getOAuthUrl("/expand/toScoreExchange?scoreExchangeId="+scoreExchangeId, uid, request, response);
			return "redirect:" + url;
		}
		
		// 兑换的列表
		ScoreExchange scoreExchange = scoreExchangeService.get(Long.parseLong(scoreExchangeId.toString()));
		request.setAttribute("scoreExchange", scoreExchange);
		
		//查找ExchangeRecord
		 List<ExchangeRecord> exchangeRecordList = exchangeRecordService.findByScoreId(scoreExchange.getId());
		 model.addAttribute("exchangeRecordList", exchangeRecordList);
		
		//查找是否有兑奖记录
		RecommendConfig recommendConfig = getRecommendConfig(uid);
		
		if(recommendConfig.getExchangeNum()>0){
			Map<String, Object> params = new HashMap<String, Object>();
			params.put("userId", uid);
			params.put("startTime", recommendConfig.getStartTime());
			params.put("endTime", recommendConfig.getEndTime());
			Integer num = wechatDaoHelper.selectExchangeRecordCount(params);
			if(num>=recommendConfig.getExchangeNum()){
				model.addAttribute("duihuan", "NO");//兑换数量已达到要求，不允许再次兑换
			}else{
				model.addAttribute("duihuan", "YES");//兑换数量未达到要求，允许再次兑换
			}
		}else{
			model.addAttribute("duihuan", "YES");//兑换数量未达到要求，允许再次兑换
		}
		
		model.addAttribute("uid", uid);
		model.addAttribute("wechatId", wechatId);
		return "modules/member/themes/expand/toScoreExchange";
	}
	
	@RequestMapping(value = "duihuanjilu")
	public String duihuanjilu(Model model, HttpServletRequest request,HttpServletResponse response) {
		String uid = request.getParameter("uid");
		String wechatId = request.getParameter("wechatId"); // OpenId
		String scoreExchangeId = request.getParameter("scoreExchangeId"); // OpenId
		
		if (StringUtils.isBlank(wechatId)) { // 没有登录先进入登录页面
			String url = getOAuthUrl("/expand/duihuanjilu?scoreExchangeId="+scoreExchangeId, uid, request, response);
			return "redirect:" + url;
		}
		
		
		//查找ExchangeRecord
		 List<ExchangeRecord> exchangeRecordList = exchangeRecordService.findByScoreId(Long.parseLong(scoreExchangeId));
		 model.addAttribute("exchangeRecordList", exchangeRecordList);
		
		
		return "modules/member/themes/expand/duihuanjilu";
	}
	

	
	@RequestMapping(value = "doExchange")
	public String doExchange(Model model, HttpServletRequest request,HttpServletResponse response){
		String uid = "2";//request.getParameter("uid");
		String wechatId = request.getParameter("wechatId");
		String exchangeId = request.getParameter("exchangeId");
		
		if (StringUtils.isBlank(wechatId)) { // 没有登录先进入登录页面
			String url = getOAuthUrl("/expand/doExchange?exchangeId="+exchangeId, uid, request, response);
			return "redirect:" + url;
		}
		RecommendConfig recommendConfig = getRecommendConfig(uid);
		/*//判断是否兑换过该商品
		Map<String,Object> maps=new HashMap<String,Object>();
		maps.put("userId", "2");
		maps.put("exchangeId", exchangeId);
		List<Map<String, String>> mapList = wechatDaoHelper.findExchangeRecord(maps);
		if(mapList!=null && mapList.size()>0){
			String message = "亲,对不起,您已兑换过该商品。";
			model.addAttribute("message", message);
			return "modules/member/themes/expand/exchangeScoreOk";
		}*/
		ScoreExchange scoreExchange=null;
		if(StringUtils.isNotEmpty(exchangeId)){
			scoreExchange = scoreExchangeService.get(Long.parseLong(exchangeId));
		}
		if("13".equals(exchangeId)){
			
		}else{
			//判断是否兑换过该活动 商品
			Map<String,Object> maps=new HashMap<String,Object>();
			Long ids[]={2l,3l,4l,5l,6l,7l,8l,9l,10l};
			List<ExchangeRecord> rlist = exchangeRecordService.findByids(ids,wechatId);
			if(rlist!=null && rlist.size()>0){
				String message = "亲,对不起,您的已兑换次数已用完。";
				model.addAttribute("message", message);
				return "modules/member/themes/expand/exchangeScoreOk";
			}
		}
		
		if(recommendConfig.getExchangeNum()>0){//限制兑换次数
			Map<String, Object> params = new HashMap<String, Object>();
			params.put("userId", uid);
			params.put("startTime", recommendConfig.getStartTime());
			params.put("endTime", recommendConfig.getEndTime());
			Integer num = wechatDaoHelper.selectExchangeRecordCount(params);
			if(num>=recommendConfig.getExchangeNum()){
				model.addAttribute("duihuan", "NO");//兑换数量已达到要求，不允许再次兑换
				//您的兑换次数已用完
				String message = "亲,对不起,您的兑换次数已经超过了该兑换商品允许的范围，感谢您的参与。";
				model.addAttribute("message", message);
				return "modules/member/themes/expand/exchangeScoreOk";
			}else{
				WechatMember member = wechatMemberService.getByWechatMemberId(new User(Long.parseLong(uid)), wechatId);
//				ScoreExchange scoreExchange = scoreExchangeService.get(Long.parseLong(exchangeId));
				if (scoreExchange.getCount() > 0) {//奖品限制兑换数量
					Map<String, Object> map = new HashMap<String, Object>();
					map.put("member_id", member.getId());
					map.put("exchange_id", exchangeId);

					String str = "";
					String cycleType  = scoreExchange.getCycleType();
					if(ScoreExchange.CYCLE_YEAR.equals(cycleType)){
						map.put("year", com.thinkgem.jeesite.common.utils.DateUtils.getYear());
						str = "今年";
					}else if(ScoreExchange.CYCLE_MONTH.equals(cycleType)){
						map.put("month", com.thinkgem.jeesite.common.utils.DateUtils.formatDate(new Date(), "yyyyMM"));
						str = "本月";
					}else if(ScoreExchange.CYCLE_DAY.equals(cycleType)){
						str = "今天";
						map.put("day",com.thinkgem.jeesite.common.utils.DateUtils.getTodayString());
					}
					Integer recordCount = memberService.selectExchangeRecordByMemberIdAndExchangeId(map);
					if (recordCount >= scoreExchange.getCount()) {
						String message = "亲,对不起,您"+str+"已经参与过" + recordCount + "次兑换活动了已经超过了该兑换商品允许的范围，感谢您的参与，";
						model.addAttribute("message", message);
						return "modules/member/themes/expand/exchangeScoreOk";
					}
				}
				String message = saveExchangeRecord(model, member,scoreExchange);
				if(!"1".equals(scoreExchange.getIskou())){
//					message = saveCouponLog(model, member,scoreExchange);
				}
				
				model.addAttribute("scoreExchange", scoreExchange);
				model.addAttribute("message", message);
				model.addAttribute("member", member);
				return "modules/member/themes/expand/exchangeScoreOk";
			}
		}else{//不限兑换次数
			WechatMember member = wechatMemberService.getByWechatMemberId(new User(Long.parseLong(uid)), wechatId);
//			ScoreExchange scoreExchange = scoreExchangeService.get(Long.parseLong(exchangeId));
			if (scoreExchange.getCount() > 0) {//奖品限制兑换数量
				Map<String, Object> map = new HashMap<String, Object>();
				map.put("member_id", member.getId());
				map.put("exchange_id", exchangeId);
				
				String str = "";
				String cycleType  = scoreExchange.getCycleType();
				if(ScoreExchange.CYCLE_YEAR.equals(cycleType)){
					map.put("year", com.thinkgem.jeesite.common.utils.DateUtils.getYear());
					str = "今年";
				}else if(ScoreExchange.CYCLE_MONTH.equals(cycleType)){
					map.put("month", com.thinkgem.jeesite.common.utils.DateUtils.formatDate(new Date(), "yyyyMM"));
					str = "本月";
				}else if(ScoreExchange.CYCLE_DAY.equals(cycleType)){
					str = "今天";
					map.put("day",com.thinkgem.jeesite.common.utils.DateUtils.getTodayString());
				}
				Integer recordCount = memberService.selectExchangeRecordByMemberIdAndExchangeId(map);
				if (recordCount >= scoreExchange.getCount()) {
					String message = "亲,对不起,您"+str+"已经参与过" + recordCount + "次兑换活动了已经超过了该兑换商品允许的范围，感谢您的参与，";
					model.addAttribute("message", message);
					return "modules/member/themes/expand/exchangeScoreOk";
				}
			}
			String message = saveExchangeRecord(model, member,scoreExchange);
			if(!"1".equals(scoreExchange.getIskou())){
//				message = saveCouponLog(model, member,scoreExchange);
			}
			model.addAttribute("member", member);
			model.addAttribute("message", message);
			model.addAttribute("member", member);
			return "modules/member/themes/expand/exchangeScoreOk";
		}
	}

	/**
	 * 保存积分兑换记录
	 * @param model
	 * @param member
	 * @param scoreExchange
	 * @param message
	 */
	private String saveExchangeRecord(Model model, WechatMember member,ScoreExchange scoreExchange) {
		String message = "恭喜您，已消费" + scoreExchange.getScore() + "积分成功兑换了【" + scoreExchange.getName() + "】.";
		if (scoreExchange.getScore() > (member.getRecommendScore()==null?0:member.getRecommendScore())) {
			message = "您的积分不足，兑换失败";//"兑换失败,您目前的积分为" + member.getRecommendScore() + "分,不能兑换积分为" + scoreExchange.getScore() + "的【" +  scoreExchange.getName() + "】.";
		} else {
			// 写兑换记录
			ExchangeRecord recorder = new ExchangeRecord();
			recorder.setCostScore(scoreExchange.getScore());
			recorder.setExchange(scoreExchange);
			recorder.setUser(scoreExchange.getUser());
			recorder.setMember(member);
			recorder.setName(scoreExchange.getName());
			recorder.setValid(false);
			recorder.setUpdateTime(new Date());
			if(scoreExchange.isAutoClear()){
				recorder.setStatus(ExchangeRecord.STATUS_CLEAR);
			}else{
				recorder.setStatus(ExchangeRecord.STATUS_NORMAL);
			}
			recorder.setEndTime(DateUtils.getDelayDate(scoreExchange.getValidDays()));
			recorder.setRemarks(message);
			// 保存兑换记录
			exchangeRecordService.save(recorder);
			
			//积分兑换数量减1
			scoreExchange.setExchangeNumber(scoreExchange.getExchangeNumber()-1);
			scoreExchangeService.save(scoreExchange);
			model.addAttribute("scoreExchange", scoreExchange);
			model.addAttribute("recorder", recorder);
			// 积分消费记录
			ScoreUtils.addRecommendScore(member, -scoreExchange.getScore(),"兑换【" + scoreExchange.getName() + "】消费积分",MemberScore.TYPE_RECOMMEND_TEMP);
		}
		return message;
	}
	
	
	/**
	 * 三级推广：我的物品
	 * @param request
	 * @param response
	 * @param model
	 * @return
	 */
	@RequestMapping(value = "myGoods")
	public String myGoods(HttpServletRequest request,HttpServletResponse response, Model model){
		String uid = request.getParameter("uid"); // userId
		String wechatId = request.getParameter("wechatId"); // OpenId
		
		if (StringUtils.isBlank(wechatId)) {
			String url = getOAuthUrl("/expand/myGoods", uid, request, response);
			return "redirect:" + url;
		}
		model.addAttribute("wechatId", wechatId);
		model.addAttribute("uid", uid);
		WechatMember member = wechatMemberService.getByWechatMemberId(new User(Long.parseLong(uid)), wechatId);
		if (AssertUtils.notNull(member)) {
			Map<String, Object> params = new HashMap<String, Object>();
			params.put("member_id", member.getId());
			List<Map<String, Object>> myGoodsList = wechatDaoHelper.selectmyGoodsBymemberId(params);
			if (AssertUtils.notNull(myGoodsList)) {
				if (myGoodsList.size()<1) {
					myGoodsList = null;
				}
			}
			model.addAttribute("myGoodsList", myGoodsList);
		}
		return "modules/member/themes/expand/myGoods";
	}
		
	/**
	 * 三级推广：删除我的物品
	 * @param request
	 * @param response
	 * @param model
	 * @return
	 */
	@RequestMapping(value = "deleteMyGoods")
	public String deleteMyGoods(HttpServletRequest request,	HttpServletResponse response, Model model) {
		String uid = request.getParameter("uid"); // userId
		String wechatId = request.getParameter("wechatId"); // OpenId
		String del_id = request.getParameter("delID");
		String type = request.getParameter("type");
			
		model.addAttribute("wechatId", wechatId);
		model.addAttribute("uid", uid);
		WechatMember member = wechatMemberService.getByWechatMemberId(new User(Long.parseLong(uid)), wechatId);
		if (AssertUtils.notNull(member)) {
			memberService.deleteMyGoods(Long.parseLong(del_id), type);
		}
		return this.myGoods(request, response, model);
	}
	
	@RequestMapping(value = "qrcode")
	public String qrcode(HttpServletRequest request,HttpServletResponse response, Model model) throws UnsupportedEncodingException{
		String uid = request.getParameter("uid");
		String wechatId = request.getParameter("wechatId");
		model.addAttribute("wechatId", wechatId);
		model.addAttribute("uid", uid);
		String  lotteryRecordId=request.getParameter("lotteryRecordId");
		String codeID = request.getParameter("codeID");

		String name = request.getParameter("name");
		name = new String(name.getBytes("ISO8859-1"), "utf-8");
		model.addAttribute("name", name);
		
		WechatMember member = wechatMemberService.getByWechatMemberId(new User(Long.parseLong(uid)), wechatId);
		Map<String, Object>  map1=new HashMap<String, Object>();
		map1.put("uid",uid);
		map1.put("memberId",member.getId());
		map1.put("codeID",codeID);
		map1.put("sourceType",10);
		/*List<Map<String,Object>> prize=(List<Map<String,Object>>)daoHelper.queryForList("com.boxin.ims.bi.selectwplotteryrecord",map1);
        if(prize.size()>0){
        	model.addAttribute("yes","1"); 
        }else{
        	model.addAttribute("yes","0");
        }*/
        model.addAttribute("codeID", codeID);
		//传入商品的用户id
		User user= member.getUser();
		model.addAttribute("user", user);

		return "modules/member/themes/expand/myQRCode";
	}
}
